Core Services
This document explains the core foundational services that power the notification bot’s infrastructure. It focuses on:
DatabaseService: MongoDB connectivity, CRUD operations, and persistence patterns
TelegramService: bot initialization, message handling, and user interaction patterns
NotificationService: orchestrator routing messages across channels (Telegram, Web Push) and managing delivery workflows It also covers service initialization patterns, dependency injection mechanisms, and how these services form the backbone of the application architecture. Practical usage examples, error handling strategies, and integration patterns are included.
The application is organized into modular layers:
Core configuration and utilities
Clients for external systems (MongoDB, Telegram Bot API)
Services for business logic (database, notifications, web push, admin)
Runners for operational tasks (update and notification dispatch)
Servers for runtime (Telegram bot and scheduler)
CLI entry point for orchestration
Diagram sources
Section sources
This section documents the three core services that underpin the application.
DatabaseService#
Responsibilities:
MongoDB connectivity and collection access via DBClient
Notice CRUD: existence checks, insertions, retrieval, and status reporting
Structured job upserts and retrieval
Placement offers merge logic with event emission for notifications
Official placement data deduplication and storage
User management: add/reactivate, deactivate, listing, and statistics
Policy management: upsert by year and retrieval
Utility helpers: serialization and statistics aggregation
Key capabilities:
Notice lifecycle: existence checks, insertion with timestamps, retrieval, and marking as sent
Job lifecycle: upsert with merge semantics and retrieval
Placement offers: merge roles and students, compute newly added students, emit events
User lifecycle: add/reactivate/deactivate and stats
Policy lifecycle: upsert by year and retrieval
Error handling:
Centralized safe printing and exception wrapping for robustness
Graceful fallbacks when collections are uninitialized
Persistence patterns:
Timestamp fields for auditability
Sent flags to coordinate delivery workflows
Content hashing for official placement data deduplication
Section sources
TelegramService#
Responsibilities:
Telegram bot initialization via TelegramClient
Message sending to default channel, specific users, and broadcasting to all users
Message formatting: MarkdownV2 and HTML conversion with escaping
Long message splitting with chunking and retry logic
Connection testing and robust retries with exponential backoff
Key capabilities:
Single and chunked message sending with parse modes
User-targeted messaging and bulk broadcasts
HTML and MarkdownV2 formatting with escaping and fallbacks
Rate-limit handling via Telegram API responses
Integration patterns:
Delegates to TelegramClient for HTTP requests
Uses DatabaseService for user lookups during broadcasts
Section sources
NotificationService#
Responsibilities:
Aggregates multiple channels (Telegram, Web Push) behind a unified interface
Routes messages to enabled channels and coordinates broadcasts
Sends unsent notices to target channels and marks them as sent upon success
Orchestrates delivery workflows across channels
Key capabilities:
Channel registration and dynamic addition
Broadcast to all users per channel
Delivery coordination for unsent notices
Results aggregation per channel
Integration patterns:
Works with DatabaseService to fetch unsent notices
Accepts channel implementations that expose channel_name and broadcast_to_all_users/send_message
Section sources
WebPushService#
Responsibilities:
Implements INotificationChannel for Web Push notifications
Uses VAPID for authentication and pywebpush for delivery
Manages subscriptions via DatabaseService and removes expired ones
Broadcasts to all users with push subscriptions
Key capabilities:
Conditional enablement based on VAPID configuration
Per-subscription push delivery with error handling
Subscription lifecycle management hooks
Section sources
AdminTelegramService#
Responsibilities:
Administrative commands for the Telegram bot
User listing, targeted broadcasting, forced updates, logs viewing, and scheduler control
Admin authentication against configured chat ID
Integration patterns:
Uses DatabaseService for user and statistics queries
Leverages TelegramService for message delivery
Interacts with scheduler daemon controls
Section sources
The system follows a layered architecture with clear separation of concerns:
Core configuration and logging
Clients for external APIs (MongoDB, Telegram Bot API)
Business services encapsulating domain logic
Runners for operational tasks
Servers for runtime exposure
CLI for orchestration
Diagram sources
DatabaseService Analysis#
DatabaseService encapsulates MongoDB operations and exposes a clean interface for notices, jobs, placement offers, users, and policies. It delegates collection access to DBClient and centralizes error handling and logging.
Diagram sources
Key operations:
Notice CRUD: existence checks, insertions, retrieval, and marking as sent
Job upsert: merge semantics for existing jobs
Placement offers: merge roles and students, compute newly added students, emit events
User management: add/reactivate/deactivate and stats
Policy management: upsert by year and retrieval
Error handling:
Safe printing and exception wrapping
Graceful fallbacks when collections are uninitialized
Section sources
TelegramService Analysis#
TelegramService provides a high-level interface for Telegram messaging, delegating HTTP interactions to TelegramClient and handling formatting and rate limits.
Diagram sources
Message flow:
Long messages are split into chunks and sent sequentially with delays
Formatting conversions support both MarkdownV2 and HTML with fallbacks
Rate-limit handling via Telegram API responses
Section sources
NotificationService Analysis#
NotificationService orchestrates delivery across multiple channels and coordinates with DatabaseService for unsent notices.
Diagram sources
Delivery workflow:
Fetch unsent notices from DatabaseService
Broadcast to target channels (Telegram/Web Push)
Mark as sent upon successful delivery
Section sources
WebPushService Analysis#
WebPushService implements INotificationChannel for Web Push notifications using VAPID authentication.
Diagram sources
Section sources
AdminTelegramService Analysis#
AdminTelegramService provides administrative commands for the Telegram bot, including user listing, broadcasting, forced updates, logs viewing, and scheduler control.
Diagram sources
Section sources
The application uses dependency injection and factory functions to wire services together.
Diagram sources
Service initialization patterns:
Factory functions create and wire services with configuration
NotificationRunner and UpdateRunner demonstrate dependency injection with optional overrides
BotServer and SchedulerServer instantiate services and configure scheduling
Section sources
DatabaseService:
Existence checks and retrieval use indexed fields (IDs) to minimize overhead
Batch operations for placement offers with merge logic reduce redundant writes
Hashing for official placement data prevents duplicate inserts
TelegramService:
Long messages are split with newline-aware chunking to respect character limits
Rate-limit handling via Telegram API responses with exponential backoff
Broadcast loops include small delays to avoid rate limits
NotificationService:
Iterates through unsent notices and broadcasts per channel, marking as sent upon success
Results aggregated per channel for visibility
WebPushService:
Conditional enablement avoids unnecessary overhead when VAPID keys are missing
Error handling for expired subscriptions to keep subscription lists healthy
[No sources needed since this section provides general guidance]
Common issues and resolutions:
MongoDB connection failures:
Verify MONGO_CONNECTION_STR environment variable and network connectivity
Check DBClient connection and ping response
Telegram bot configuration:
Ensure TELEGRAM_BOT_TOKEN and TELEGRAM_CHAT_ID are set
Use test_connection to validate bot token
Rate limiting:
Telegram API returns 429 with Retry-After header; service waits and retries
Adjust broadcast delays if still encountering limits
Web Push:
Confirm VAPID keys are configured; service disables itself if missing
Expired subscriptions are removed automatically on WebPushException with 404/410
Logging:
Use setup_logging to configure file and stream handlers
Enable verbose mode (-v) for debug-level logs
Section sources
The core services provide a robust, modular foundation for the notification bot:
DatabaseService ensures reliable persistence and efficient data operations
TelegramService delivers messages with formatting and resilience
NotificationService orchestrates cross-channel delivery and integrates with DatabaseService
WebPushService adds modern browser notifications with VAPID support
AdminTelegramService enables operational control via Telegram
Dependency injection and factory patterns promote testability and maintainability
These components work together to deliver timely, formatted notifications across multiple channels while maintaining clear separation of concerns and strong error handling.